# Inspired by persistent_cloud.yml, but the VM is not started automatically.
# This only works with modern Fedora for now, not with RHEL/CentOS.

---
- include_vars: dir=/srv/web/infra/ansible/vars/all/ ignore_files=README

- name: check if the server is up, needs to be pre-started
  local_action: shell nc -w 5 {{ inventory_hostname }} 22 < /dev/null
  register: host_is_up
  changed_when: false
  check_mode: no

- name: birthday=on - drop the old known host entries
  local_action: known_hosts path={{item}}
                host={{ inventory_hostname }}
                state=absent
  with_items:
  - /root/.ssh/known_hosts
  when: birthday is defined

- name: gather the temporary ssh host key from the new instance
  local_action: command ssh-keyscan -t ed25519 {{ inventory_hostname }}
  register: hostkey
  when: birthday is defined

- name: add new ssh host key (until we can sign it)
  local_action: known_hosts path={{item}} key="{{ hostkey.stdout }}"
                host={{ inventory_hostname }} state=present
  with_items:
  - /root/.ssh/known_hosts
  when: birthday is defined

# from https://github.com/praiskup/ansible-role-fix-root-ssh
- name: allow root ssh connections
  lineinfile:
    path: /etc/cloud/cloud.cfg
    regexp: '^disable_root:'
    line: 'disable_root: 0'
  remote_user: fedora
  become: true
  become_user: root
  when: birthday is defined

- name: use the same authorized_keys
  replace:
    path: /root/.ssh/authorized_keys
    regexp: '.*Please login as the user.* ssh-rsa '
    replace: 'ssh-rsa '
    backup: yes
  remote_user: fedora
  become: true
  become_user: root
  when: birthday is defined

#
# Next we try and gather facts. If the host doesn't have python2 this will fail.
#

- name: gather facts
  setup:
  check_mode: no
  ignore_errors: true
  register: facts

#
# If that failed, then we use the raw module to install things
#

- name: install python3 and dnf stuff
  raw: sudo dnf -y install python3-dnf python3-libselinux python3
  when:
  - birthday is defined
  - facts is failed

# - name: Include SSH config
#   import_role: name=basessh
